<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>局域网聊天</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3b82f6',
            secondary: '#10b981',
            dark: '#1e293b',
            light: '#f8fafc'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .scrollbar-hide {
        -ms-overflow-style: none;
        scrollbar-width: none;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
      .message-in {
        animation: fadeInRight 0.3s ease forwards;
      }
      .message-out {
        animation: fadeInLeft 0.3s ease forwards;
      }
      @keyframes fadeInRight {
        from {
          opacity: 0;
          transform: translateX(-10px);
        }
        to {
          opacity: 1;
          transform: translateX(0);
        }
      }
      @keyframes fadeInLeft {
        from {
          opacity: 0;
          transform: translateX(10px);
        }
        to {
          opacity: 1;
          transform: translateX(0);
        }
      }
    }
  </style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen font-sans text-slate-800">
  <div class="container mx-auto px-4 py-8 max-w-4xl">
    <!-- 聊天头部 -->
    <div class="bg-white rounded-t-xl shadow-lg overflow-hidden">
      <div class="flex items-center justify-between p-4 border-b border-slate-200">
        <div class="flex items-center space-x-3">
          <i class="fa fa-comments text-primary text-2xl"></i>
          <h1 class="text-xl font-bold text-dark">局域网聊天</h1>
        </div>
        <div id="status-indicator" class="flex items-center">
          <span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span>
          <span class="text-sm text-slate-500">未连接</span>
        </div>
      </div>

      <!-- 用户名设置 -->
      <div id="username-modal" class="p-6">
        <h2 class="text-lg font-semibold mb-4">设置用户名</h2>
        <div class="flex">
          <input type="text" id="username" placeholder="请输入你的用户名" 
            class="flex-1 px-4 py-2 border border-slate-300 rounded-l-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
          <button id="join-chat" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-r-lg transition-all duration-200">
            加入聊天
          </button>
        </div>
        <p class="text-xs text-slate-500 mt-2">用户名不能为空</p>
      </div>

      <!-- 聊天区域 -->
      <div id="chat-container" class="hidden">
        <div id="messages" class="h-[400px] overflow-y-auto p-4 scrollbar-hide bg-slate-50">
          <!-- 消息将在这里动态添加 -->
        </div>

        <!-- 发送区域 -->
        <div class="p-4 border-t border-slate-200 bg-white">
          <div class="flex space-x-2">
            <input type="text" id="message-input" placeholder="输入消息..." 
              class="flex-1 px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
            <button id="send-button" disabled 
              class="bg-slate-300 text-white px-5 py-3 rounded-lg transition-all duration-200 hover:bg-primary/90">
              <i class="fa fa-paper-plane"></i> 发送
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="text-center text-xs text-slate-500 mt-4">
      <p>局域网聊天应用 | 使用 WebSocket 技术</p>
    </div>
  </div>

  <script>
    // 全局变量
    let ws;
    let username = '';
    const messagesContainer = document.getElementById('messages');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const usernameInput = document.getElementById('username');
    const joinChatButton = document.getElementById('join-chat');
    const usernameModal = document.getElementById('username-modal');
    const chatContainer = document.getElementById('chat-container');
    const statusIndicator = document.getElementById('status-indicator');

    // 连接WebSocket服务器
    function connectWebSocket() {
      // 从URL获取服务器地址，如果没有则使用默认值
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const serverAddress = `${protocol}//${window.location.host}/ws?username=${encodeURIComponent(username)}`;
      
      ws = new WebSocket(serverAddress);
      
      ws.onopen = () => {
        updateStatus('connected');
        console.log('WebSocket连接已建立');
        // 发送加入消息
        sendMessage(`已加入聊天`, 'system');
      };
      
      ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        addMessageToUI(message);
      };
      
      ws.onclose = () => {
        updateStatus('disconnected');
        console.log('WebSocket连接已关闭');
        addMessageToUI({
          content: '与服务器的连接已断开，正在尝试重新连接...',
          type: 'system',
          timestamp: new Date().toLocaleTimeString()
        });
        
        // 3秒后尝试重新连接
        setTimeout(connectWebSocket, 3000);
      };
      
      ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        updateStatus('error');
      };
    }

    // 发送消息
    function sendMessage(content, type = 'user') {
      if (!ws || ws.readyState !== WebSocket.OPEN) {
        addMessageToUI({
          content: '无法发送消息: 未连接到服务器',
          type: 'error',
          timestamp: new Date().toLocaleTimeString()
        });
        return;
      }
      
      const message = {
        username,
        content,
        type,
        timestamp: new Date().toLocaleTimeString()
      };
      console.log(message)
      ws.send(JSON.stringify(message));
      
      if (type === 'user') {
        // 清空输入框
        messageInput.value = '';
        // 添加自己发送的消息到UI
        addMessageToUI({
          ...message,
          isSelf: true
        });
      }
    }

    // 添加消息到UI
    function addMessageToUI(message) {
      const messageDiv = document.createElement('div');
      messageDiv.className = 'mb-4';
      
      let messageContent;
      if (message.type === 'system') {
        messageContent = `
          <div class="flex justify-center">
            <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-xs">
              ${message.content}
            </span>
          </div>
        `;
      } else if (message.type === 'error') {
        messageContent = `
          <div class="flex justify-center">
            <span class="px-3 py-1 bg-red-100 text-red-800 rounded-full text-xs">
              ${message.content}
            </span>
          </div>
        `;
      } else {
        const alignment = message.isSelf ? 'justify-end' : 'justify-start';
        const bgColor = message.isSelf ? 'bg-primary text-white' : 'bg-white shadow-sm';
        const messageClass = message.isSelf ? 'message-out' : 'message-in';
        
        messageContent = `
          <div class="flex ${alignment}">
            <div class="max-w-[80%] ${bgColor} p-3 rounded-lg ${messageClass}">
              ${message.isSelf ? '' : `<div class="text-xs text-slate-400 mb-1">${message.username}</div>`}
              <p>${message.content}</p>
              <div class="text-xs text-right text-slate-400 mt-1">${message.timestamp}</div>
            </div>
          </div>
        `;
      }
      
      messageDiv.innerHTML = messageContent;
      messagesContainer.appendChild(messageDiv);
      
      // 滚动到底部
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 更新连接状态
    function updateStatus(status) {
      const statusText = statusIndicator.querySelector('span');
      const statusDot = statusIndicator.querySelector('span:first-child');
      
      if (status === 'connected') {
        statusText.textContent = '已连接';
        statusDot.className = 'w-2 h-2 rounded-full bg-green-500 mr-2';
        sendButton.disabled = false;
        sendButton.className = 'bg-primary text-white px-5 py-3 rounded-lg transition-all duration-200 hover:bg-primary/90';
      } else if (status === 'disconnected') {
        statusText.textContent = '未连接';
        statusDot.className = 'w-2 h-2 rounded-full bg-red-500 mr-2';
        sendButton.disabled = true;
        sendButton.className = 'bg-slate-300 text-white px-5 py-3 rounded-lg transition-all duration-200 hover:bg-primary/90';
      } else if (status === 'error') {
        statusText.textContent = '连接错误';
        statusDot.className = 'w-2 h-2 rounded-full bg-yellow-500 mr-2';
        sendButton.disabled = true;
        sendButton.className = 'bg-slate-300 text-white px-5 py-3 rounded-lg transition-all duration-200 hover:bg-primary/90';
      }
    }

    // 事件监听
    joinChatButton.addEventListener('click', () => {
      username = usernameInput.value.trim();
      if (username) {
        usernameModal.classList.add('hidden');
        chatContainer.classList.remove('hidden');
        connectWebSocket();
      } else {
        alert('请输入有效的用户名');
      }
    });

    sendButton.addEventListener('click', () => {
      const content = messageInput.value.trim();
      if (content) {
        sendMessage(content);
      }
    });

    messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        const content = messageInput.value.trim();
        if (content) {
          sendMessage(content);
        }
      }
    });

    // 页面加载完成后聚焦到用户名输入框
    document.addEventListener('DOMContentLoaded', () => {
      usernameInput.focus();
    });
  </script>
</body>
</html>    